package com.mvp.lt.airlineview.location;

import android.Manifest;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Criteria;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.TileOverlay;
import com.amap.api.maps.model.TileOverlayOptions;
import com.amap.api.maps.model.UrlTileProvider;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.TranslateAnimation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.mvp.lt.airlineview.App;
import com.mvp.lt.airlineview.LocationSearchBean;
import com.mvp.lt.airlineview.R;
import com.mvp.lt.airlineview.base.BaseActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.mvp.lt.airlineview.map.HeritageScopeTileProvider;
import com.mvp.lt.airlineview.map.MapCalculationLogLatDistance;
import com.mvp.lt.airlineview.map.MapCreateManager;
import com.mvp.lt.airlineview.utils.LogUtil;
import com.mvp.lt.airlineview.utils.ToastUtils;
import com.mvp.lt.airlineview.utils.UIUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * $activityName
 *
 * @author LiuTao
 * @date 2019/3/27/027
 */


public class ADRegionalPromotionActivity extends BaseActivity implements TextWatcher, Inputtips.InputtipsListener {
    @BindView(R.id.map_view)
    MapView mMapView;

    @BindView(R.id.input_edittext)
    AutoCompleteTextView inputEdittext;
    @BindView(R.id.search_bar_layout)
    RelativeLayout searchBarLayout;
    @BindView(R.id.inputlist)
    RecyclerView mRecyclerView;
    @BindView(R.id.clear_iv)
    ImageView clearIv;
    private boolean isFirstLoc = true;
    private Marker screenMarker;
    private int radius = 0;
    private Circle mCircle;
    private String mAddress;
    private GeocodeSearch mGeocoderSearch;
    private String mAddressName;
    private String city = "湖南";
    private Marker mTagmarker;
    private LocationPositionAdapter mLocationPositionAdapter;
    LatLng leftLatLng = new LatLng(27.259653, 111.54144);
    LatLng rightLatLng = new LatLng(27.259653, 111.64244);
    private TileOverlay mTileOverlay;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regional_promotion);
        ButterKnife.bind(this);
        initView();
        inputEdittext.addTextChangedListener(this);
        // initLocation();
        MapCreateManager.getMapManager().setMapView(this,mMapView).buildMap(savedInstanceState);
        //加载自定义wms
//        HeritageScopeTileProvider tileProvider = new HeritageScopeTileProvider();
//        MapCreateManager.getMapManager().getaMap().addTileOverlay(new TileOverlayOptions()
//                .tileProvider(tileProvider)
//                .zIndex(-0.1f)
//                .diskCacheDir("/storage/amap/cache")
//                .diskCacheEnabled(true)
//                .diskCacheSize(100));
        LogUtil.e("Marker", "=================getTileUrl=================" );
        MapCreateManager.getMapManager().addMarker(leftLatLng);//左边的点 黄色
        MapCreateManager.getMapManager().addMarker1(rightLatLng);//右边边的点 绿色
        //划线
        MapCreateManager.getMapManager().drawLine(leftLatLng, rightLatLng);
        //求左边点的外扩点 向左外扩
        LatLng latLng0 = MapCalculationLogLatDistance.getDistanceExpansionPoint(rightLatLng.longitude, rightLatLng.latitude, leftLatLng.longitude, leftLatLng.latitude, 100);
        MapCreateManager.getMapManager().addMarker3(latLng0);
        MapCreateManager.getMapManager().drawLine(leftLatLng, latLng0);
        //求右边点的外扩点 向右外扩
        LatLng latLng1 = MapCalculationLogLatDistance.getDistanceExpansionPoint(leftLatLng.longitude, leftLatLng.latitude, rightLatLng.longitude, rightLatLng.latitude, 100);

        MapCreateManager.getMapManager().addMarker2(latLng1);
        MapCreateManager.getMapManager().drawLine(rightLatLng, latLng1);

        MapCreateManager.getMapManager().setOnMarkerDragListener(new AMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {
                LogUtil.e("Marker", "开始拖动" + "");
                //航点拖拽
                //带加号的航点拖拽
                WayPointLineMapUtils.getInstance().differentMarkerTypeDragStart(marker);
            }


            @Override
            public void onMarkerDrag(Marker marker) {
                //航点拖拽
                //带加号的航点拖拽
                WayPointLineMapUtils.getInstance().differentMarkerTypeDrag(marker);
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                LogUtil.e("Marker", "结束拖动" + "");
                WayPointLineMapUtils.getInstance().differentMarkerTypeDragEnd(marker);
            }

        });

        MapCreateManager.getMapManager().setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.getObject() != null) {
                    try {
                        //marker点的类型 常量类 MapMarkerTypeConstant
                        int type = (int) marker.getObject();
                        WayPointLineMapUtils.getInstance().onMarkerClick(marker, type);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                return false;
            }
        });

        MapCreateManager.getMapManager().setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                WayPointLineMapUtils.getInstance().onMapClick(latLng);
            }
        });
//        loadOfflineTile();
    }


    public void loadOfflineTile() {
        final String url = "file:///storage/emulated/0/tiles/tiles/%d/%d/%d.jpg";
        TileOverlayOptions tileOverlayOptions =
                new TileOverlayOptions().tileProvider(new UrlTileProvider(256, 256) {

                    @Override
                    public URL getTileUrl(int x, int y, int zoom) {
                        try {
                            LogUtil.e("Marker", "getTileUrl" + ":" + x + ",y:" + y + ",zoom:" + zoom);
                            return new URL(String.format(url, zoom, x, y));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                });
        tileOverlayOptions.diskCacheEnabled(true)
                .diskCacheDir("/storage/emulated/0/amap/tilecache")
                .diskCacheSize(100000)
                .memoryCacheEnabled(true)
                .memCacheSize(100000)
                .zIndex(-0.1f);
        mTileOverlay = MapCreateManager.getMapManager().getaMap().addTileOverlay(tileOverlayOptions);
    }

    private void initView() {
        initMapView();
        initAdapter();
        clearIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputEdittext.setText("");
                mLocationPositionAdapter.setNewData(null);
                mRecyclerView.setVisibility(View.GONE);
            }
        });
        //反转航点
        findViewById(R.id.bt_reverse_map).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WayPointLineMapUtils.getInstance().reversalData();
            }
        });
        //删除航点
        findViewById(R.id.bt_revoke_map).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WayPointLineMapUtils.getInstance().deleteCurrentData();
            }
        });
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(App.getContext()));
        mLocationPositionAdapter = new LocationPositionAdapter(null);
        mRecyclerView.setAdapter(mLocationPositionAdapter);
        mLocationPositionAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                try {
                    mRecyclerView.setVisibility(View.GONE);
                    LatLonPoint latLonPoint = mLocationPositionAdapter.getData().get(position).getLatLonPoint();
                    MapCreateManager.getMapManager().getaMap().moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude())));
                    LatLng latLng = new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
                    addMarkersToMap(latLng);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void initMapView() {

        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 在地图上添加marker
     */
    private void addMarkersToMap() {

        addMarkerInScreenCenter();

    }

    /**
     * 在屏幕中心添加一个Marker
     */
    private void addMarkerInScreenCenter() {
        LatLng latLng = MapCreateManager.getMapManager().getaMap().getCameraPosition().target;
        Point screenPosition = MapCreateManager.getMapManager().getaMap().getProjection().toScreenLocation(latLng);
        screenMarker = MapCreateManager.getMapManager().getaMap().addMarker(new MarkerOptions()
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.purple_pin)));
        //设置Marker在屏幕上,不跟随地图移动
        screenMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        getAddress(new LatLonPoint(screenMarker.getPosition().latitude, screenMarker.getPosition().longitude));
    }

    /**
     * 在地图上添加marker
     */
    private void addMarkersToMap(LatLng latLng) {
        if (mTagmarker == null) {
            MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                    .position(latLng)
                    .draggable(true);
            mTagmarker = MapCreateManager.getMapManager().getaMap().addMarker(markerOption);
        } else {
            mTagmarker.setPosition(latLng);
        }
    }


    /**
     * 屏幕中心marker 跳动
     */
    public void startJumpAnimation() {

        if (screenMarker != null) {
            //根据屏幕距离计算需要移动的目标点
            final LatLng latLng = screenMarker.getPosition();
            Point point = MapCreateManager.getMapManager().getaMap().getProjection().toScreenLocation(latLng);
            point.y -= UIUtils.dip2Px(125);
            LatLng target = MapCreateManager.getMapManager().getaMap().getProjection().fromScreenLocation(point);
            //使用TranslateAnimation,填写一个需要移动的目标点
            Animation animation = new TranslateAnimation(target);
            animation.setInterpolator(new Interpolator() {
                @Override
                public float getInterpolation(float input) {
                    // 模拟重加速度的interpolator
                    if (input <= 0.5) {
                        return (float) (0.5f - 2 * (0.5 - input) * (0.5 - input));
                    } else {
                        return (float) (0.5f - Math.sqrt((input - 0.5f) * (1.5f - input)));
                    }
                }
            });

            //整个移动所需要的时间
            animation.setDuration(600);
            //设置动画
            screenMarker.setAnimation(animation);
            //开始动画
            screenMarker.startAnimation();
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart() {

                }

                @Override
                public void onAnimationEnd() {
                    if (radius > 0) {
                        ToastUtils.showToast("当前公里值为" + radius);
                        addPolylinescircle(latLng, radius);

                    }
                }
            });

        } else {
            LogUtil.i("amap", "screenMarker is null");
        }
    }

    /**
     * @param centerpoint 中心点坐标
     * @param radius      半径 1公里(km)=1000米(m)
     */
    public void addPolylinescircle(LatLng centerpoint, @IntRange(from = 0, to = 5) int radius) {
        if (mCircle == null) {
            mCircle = MapCreateManager.getMapManager().getaMap().addCircle(new CircleOptions()
                    .strokeColor(Color.argb(160, 1, 1, 1))
                    .fillColor(Color.argb(90, 253, 119, 153))
                    .strokeWidth(5));
        }
        mCircle.setRadius(radius * 1000);
        mCircle.setCenter(centerpoint);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        WayPointLineMapUtils.getInstance().onDestroy();
    }


    /**
     * 响应逆地理编码
     */
    public void getAddress(final LatLonPoint latLonPoint) {
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
        mGeocoderSearch.getFromLocationAsyn(query);
    }


    private boolean mCanMockPosition = false;
    private LocationManager mLocationManager;
    boolean hasAddTestProvider = false;

    public void initLocation() {
        mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        App.getInstance().setLocationManager(mLocationManager);
        mCanMockPosition = (Settings.Secure.getInt(getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, 0) != 0) || Build.VERSION.SDK_INT > 22;
        if (mCanMockPosition && hasAddTestProvider == false) {
            try {
                LocationProvider provider = mLocationManager.getProvider(LocationManager.GPS_PROVIDER);
                if (provider != null) {
                    mLocationManager.addTestProvider(
                            provider.getName()
                            , provider.requiresNetwork()
                            , provider.requiresSatellite()
                            , provider.requiresCell()
                            , provider.hasMonetaryCost()
                            , provider.supportsAltitude()
                            , provider.supportsSpeed()
                            , provider.supportsBearing()
                            , provider.getPowerRequirement()
                            , provider.getAccuracy());
                } else {

                    mLocationManager.addTestProvider(
                            LocationManager.GPS_PROVIDER
                            , true, true, false, false, true, true, true
                            , Criteria.POWER_HIGH, Criteria.ACCURACY_FINE);
                }
                mLocationManager.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
                mLocationManager.setTestProviderStatus(LocationManager.GPS_PROVIDER, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
                // 模拟位置可用
                hasAddTestProvider = true;
                mCanMockPosition = true;
            } catch (SecurityException e) {
                mCanMockPosition = false;
                e.printStackTrace();
                ToastUtils.showToast("模拟位置失败");
            }
        }
    }


    /**
     * 转高德地图经纬度
     *
     * @param sourceLatLng
     * @return
     */
    public LatLng latLngToGDLatLng(LatLng sourceLatLng) {
        CoordinateConverter converter = new CoordinateConverter(App.getContext());
        // CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS);
        // sourceLatLng待转换坐标点 LatLng类型
        converter.coord(sourceLatLng);
        // 执行转换操作
        LatLng desLatLng = converter.convert();
        return desLatLng;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (TextUtils.isEmpty(s)) {
            mRecyclerView.setVisibility(View.GONE);
            return;
        } else if (TextUtils.isEmpty(s.toString().trim())) {
            mRecyclerView.setVisibility(View.GONE);
            return;
        } else {
            String newText = s.toString().trim();
            InputtipsQuery inputquery = new InputtipsQuery(newText, city);
            inputquery.setCityLimit(true);
            Inputtips inputTips = new Inputtips(ADRegionalPromotionActivity.this, inputquery);
            inputTips.setInputtipsListener(this);
            inputTips.requestInputtipsAsyn();
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        mRecyclerView.setVisibility(View.VISIBLE);
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            List<LocationSearchBean> locationSearchBeans = new ArrayList<LocationSearchBean>();
            if (tipList != null) {
                int size = tipList.size();
                for (int i = 0; i < size; i++) {
                    Tip tip = tipList.get(i);
                    if (tip != null && tipList.get(i).getPoint() != null) {
                        locationSearchBeans.add(new LocationSearchBean(tipList.get(i).getName(), tipList.get(i).getDistrict(), tipList.get(i).getPoint()));

                    }
                }
            }
            mLocationPositionAdapter.setNewData(locationSearchBeans);
        } else {
            ToastUtils.showToast(rCode);
        }
    }
}
